package com.bobby.service.impl;

import com.bobby.dao.BookDao;
import com.bobby.dao.OrderDao;
import com.bobby.dao.OrderItemDao;
import com.bobby.dao.impl.BookDaoImpl;
import com.bobby.dao.impl.OrderDaoImpl;
import com.bobby.dao.impl.OrderItemDaoImp;
import com.bobby.pojo.*;
import com.bobby.service.OrderService;
import com.bobby.test.OrderDaoTest;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description TODO
 * @Date 2020/8/16 15:40
 * @Created wenjunpei
 */
public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = new OrderDaoImpl();

    private OrderItemDao orderItemDao = new OrderItemDaoImp();

    private BookDao bookDao = new BookDaoImpl();

    @Override
    public String createOrder(Cart cart, Integer userId) throws SQLException {
        String orderId = String.valueOf(System.currentTimeMillis() + "" + userId);
        Order order = new Order();
        order.setCreateTime(new Date());
        order.setOrderId(orderId);
        order.setPrice(cart.getTotalPrice());
        order.setStatus(0);
        order.setUserId(userId);
        orderDao.saveOrder(order);


        for(Map.Entry<Integer, CartItem> entry : cart.getCartItemMap().entrySet()) {
            Integer bookId = entry.getKey();
            CartItem cartItem = entry.getValue();
            OrderItem orderItem = new OrderItem(null,cartItem.getName(),cartItem.getCount(),cartItem.getPrice(),cartItem.getTotalPrice(),orderId);
            orderItemDao.saveOrderItem(orderItem);

            Book book = bookDao.queryBookById(bookId);
            book.setSales(book.getSales() + cartItem.getCount());
            book.setStock(book.getStock() - cartItem.getCount());
            bookDao.updateBook(book);
        }


        //清空购物车
        cart.clear();

        return orderId;
    }

    @Override
    public List<Order> showAllOrders() throws SQLException {
        return orderDao.queryOrders();
    }

    @Override
    public void sendOrder(String orderId) throws SQLException {
        orderDao.changerOrderStatus(orderId,1);
    }

    @Override
    public List<OrderItem> showOrderDetail(String orderId) throws SQLException {
        return orderItemDao.queryOrderItemByOrderId(orderId);
    }

    @Override
    public List<Order> showMyOrders(Integer userId) throws SQLException {
        return orderDao.queryOrdersByUserId(userId);
    }

    @Override
    public void receiveOrder(String orderId) throws SQLException {
        orderDao.changerOrderStatus(orderId,2);
    }
}
